package com.ibm.mediumserver;

import java.net.ServerSocket;
import java.net.Socket;

public class MediumServer {
	private static final short port = 777;

	public static void main(String args[]) {
		try {
			// creates the ServerSocket and "tells" OS of its
			// interest in requests coming to the
			// specified port

			ServerSocket serverSocket = new ServerSocket(port);

			// create the Queue that holds the requests
			Queue requestQue = new Queue(5, 10);

			// create the Queue that holds the runnables
			Queue runnableQue = new Queue(10, 10, MediumRunnable.class);

			// create the Runnable pool that contains 10
			// runnables
			for (int i = 0; i < 10; i++) {
				Runnable runner = new MediumRunnable();
				runnableQue.add(runner);
			}

			// create the Thread pool that contains 5 Threads
			for (int i = 0; i < 5; i++) {
				Thread thread = new TPThreadToo(requestQue, runnableQue);
				thread.start();
			}

			System.out.println("Server started properly");

			// now let's wait and accept connections
			while (true) {
				try {
					// get the request
					Socket request = serverSocket.accept();

					// get a runnable
					MediumRunnable runner = (MediumRunnable) runnableQue.next();

					// re-initialize the runner
					runner.init(request);
					// add it to the que so a thread can handle it
					requestQue.add(runner);
				} catch (java.io.IOException ioe) {
					System.out.println("Problems handling request" + ioe);
				}
			}
		} catch (Exception e) {
			System.out.println("Problem starting the " + "server....");
			e.printStackTrace(System.out);
			System.exit(-1);
		}
	}
}
